package com.heima.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.domain.HhPatient;
import com.heima.domain.HhUsers;
import com.heima.domain.HhUsersAccount;
import com.heima.dto.RegisterDto;
import com.heima.mapper.HhPatientMapper;
import com.heima.mapper.HhUsersAccountMapper;
import com.heima.mapper.HhUsersMapper;
import com.heima.service.IHhUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.vo.LoginOpenIdVo;
import com.heima.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 小程序用户 服务实现类
 * </p>
 *
 * @author 黑马程序员
 * @since 2023-01-29
 */
@Slf4j
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class HhUsersServiceImpl extends ServiceImpl<HhUsersMapper, HhUsers> implements IHhUsersService {
    @Autowired
    private HhUsersMapper hhUsersMapper;
    @Autowired
    private HhUsersAccountMapper hhUsersAccountMapper;
    @Autowired
    private HhPatientMapper hhPatientMapper;

    @Override
    public LoginOpenIdVo getOpenId(String code) {
        // 1.入参判断
        // isBlank 代表变量不存在
        boolean empty = StringUtils.isEmpty(code);
        if (empty) {
            throw new RuntimeException("入参不能为空");
        }
        // 2.请求微信服务的接口
        // 2.1:请求什么接口
        // 2.2用什么请求接口 http://localhost:9090/sns/jscode2session
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:9090/sns/jscode2session";
        url += "?appid=wxe6f0c12631e361d0";
        url += "&secret=6cb71ccff4a8bb85c153ad6ec996855c";
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        Map response = restTemplate.getForObject(url, Map.class);
        if (response == null) {
            throw new RuntimeException("微信调用异常");
        }
        log.info("MAP是{}", response);

        // 3.解析微信接口的返回值
        Object openId = response.get("openid");

        // 4.将openId返回前端
        LoginOpenIdVo vo = new LoginOpenIdVo();
        vo.setOpenId((String) openId);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public RegisterVo register(RegisterDto dto) {
        if (dto == null) {
            throw new RuntimeException("入参不能为空");
        }
        // 2.检查openId+phone是否存在数据库中
        LambdaQueryWrapper<HhUsers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HhUsers::getOpenId, dto.getOpenId());
        wrapper.eq(HhUsers::getPhone, dto.getPhone());
        HhUsers hhUsers = hhUsersMapper.selectOne(wrapper);
        Map<String, Object> payload = new HashMap<>();
        // 3.不存在
        // 创建新用户
        if (hhUsers == null) {
            HhUsers users = new HhUsers();
            BeanUtils.copyProperties(dto, users);
            users.setAvatar(dto.getAvatarUrl());
            users.setNickname(dto.getNickName());
            int Result1 = hhUsersMapper.insert(users);
            if (Result1 != 1) {
                throw new RuntimeException("用户表插入失败");
            }
            HhUsersAccount account = new HhUsersAccount();
            account.setUserId(users.getId());
            account.setBalance(0);
            int Result2 = hhUsersAccountMapper.insert(account);
            if (Result2 != 1) {
                throw new RuntimeException("账户插入失败");

            }
            HhPatient patient = new HhPatient();
            patient.setUserId(users.getId());
            patient.setAddress(dto.getCountry() + " " + dto.getProvince() + " " + dto.getCity());
            patient.setCardNumber("");
            patient.setCardType(0);
            patient.setIsDefault(1);
            patient.setName(dto.getNickName());
            patient.setPhone(dto.getPhone());
            patient.setTags("本人");
            int Result3 = hhPatientMapper.insert(patient);
            if (Result3 != 1) {
                throw new RuntimeException("就诊人插入失败");
            }
            payload.put("id", users.getId());
            payload.put("openId", users.getOpenId());
        } else {

            payload.put("id", hhUsers.getId());
            payload.put("openId", hhUsers.getOpenId());
        }
        // 4.存在
        // 生成token返回前端
        String token = JWTUtil.createToken(null, payload, "heima3306".getBytes());
        RegisterVo vo = new RegisterVo();
        vo.setToken(token);
        return vo;
    }
}
